package com.System.LearnSystemStudent;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.System.LearnSystem.Result;
import com.System.LearnSystem.Token;
import com.System.LearnSystem.sqlConnection;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

class Message3 extends Message2	//用于临时储存客户端发来的请求信息
{
	private String lesson;
	private int day;        //用于记录哪一天的课
	private String number1; //用于记录哪节课
	private String number2;	//若有第三课时则用这个标记
	
	public Message3()
	{
		
	}
	
	
	public String getlesson() {
		return lesson;
	}

	public void setlesson(String lesson) {
		this.lesson = lesson;
	}

	public int getDay() {
		return day;
	}

	public void setDay(int day) {
		this.day = day;
	}

	public String getNumber1() {
		return number1;
	}

	public void setNumber1(String number1) {
		this.number1 = number1;
	}

	public String getNumber2() {
		return number2;
	}

	public void setNumber2(String number2) {
		this.number2 = number2;
	}

	
}

@WebServlet("/stu/addLesson")
public class addLesson extends HttpServlet{
	public void doPut(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
	{
		StringBuilder json = new StringBuilder();//读取json请求
        BufferedReader reader = req.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            json.append(line);
        }
        String jsonStr = json.toString();     
        ObjectMapper objectMapper = new ObjectMapper(); 
        objectMapper.registerModule(new JavaTimeModule());//注册驱动保证序列化
        Message3 message = objectMapper.readValue(jsonStr, Message3.class);
        
        res.setContentType("application/json;charset=UTF-8");//设置响应格式
        PrintWriter out = res.getWriter();
        if(message.gettoken()!=null)
        {
        	if(Token.checkToken(message.gettoken())&&"STUDENT".equals(message.getrole()))//验证令牌和身份
        	{         		        		
	        	try (Connection conn = sqlConnection.getConnection();Statement statement = conn.createStatement())
	        	{
	        		String checksql = "SELECT "+message.getNumber1()+" FROM "+message.getusername()+" WHERE class = "+message.getDay()+";";
	        		System.out.println(checksql);
	        		ResultSet checkrs = statement.executeQuery(checksql);
	        		checkrs.next();
	        		if(checkrs.getString(message.getNumber1())==null)
	        		{	
	        			if(message.getNumber2()==null)	
		        		{
		        			String sql ="UPDATE " +message.getusername()  //添加课程的语句
		        					   +" SET "+message.getNumber1()+" = '"+message.getlesson()+"'"
		        					   +" WHERE class = "+ message.getDay();
		        			int Line = statement.executeUpdate(sql);
		        			System.out.println("受影响的行数为："+Line);	        			
		        		}
		        		else
		        		{
		        			String sql ="UPDATE " +message.getusername()  //添加课程的语句
				 					   +" SET "+message.getNumber1()+" = '"+message.getlesson()+"',"+message.getNumber2()+" = '"+message.getlesson()+"'"
				 					   +" WHERE class = "+ message.getDay();
							int Line = statement.executeUpdate(sql);
							System.out.println("受影响的行数为："+Line);	        			
		        		}
		        			String sql = "SELECT * FROM "+message.getusername();//访问课表的语句
		        			ResultSet rs = statement.executeQuery(sql);
	        			int n = 0;
	        			Schedule schedule = new Schedule(); 
	        			while(rs.next()) //读取每天的课表
	        			{
	        				schedule.setlesson(n,1,rs.getString("FIRST"));
	        				schedule.setlesson(n,2,rs.getString("Second"));
	        				schedule.setlesson(n,3,rs.getString("M"));
	        				schedule.setlesson(n,4,rs.getString("Third"));
	        				schedule.setlesson(n,5,rs.getString("N"));
	        				schedule.setlesson(n,6,rs.getString("Fourth"));
	        				schedule.setlesson(n,7,rs.getString("Fifth"));
	        				n++;
	        			}
	        			Result<Schedule> result = Result.success(schedule);
	        			out.println(objectMapper.writeValueAsString(result));
		        	}
	        		else        			
	        		{
	        			Result<Object> result = Result.success();
	        			result.setMessage("课程存在冲突");
	        			out.println(objectMapper.writeValueAsString(result));
	        		}
	        	} catch (SQLException e) {
	        		System.err.println("SQL 错误码: " + e.getErrorCode());
		          	System.err.println("SQL 错误消息: " + e.getMessage());
		          	e.printStackTrace();
				}
	        	
        	}
        	else
        	{
        		Result<Object> result = Result.error(401,"非授权访问");
        		out.println(objectMapper.writeValueAsString(result));
        	}
        }
        else
        {
        	Result<Object> result = Result.error(401,"非授权访问");
        	out.println(objectMapper.writeValueAsString(result));
        }
	}

}
